package com.lifeng.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lifeng on 2018/5/9.
 */
@Component
public class MySafeZuulFilter extends ZuulFilter{
    private static final Logger log = LoggerFactory.getLogger(MySafeZuulFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        log.info("安全请求过滤器执行了。。。");
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().getBoolean("isOK");
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req =ctx.getRequest();
        String username = req.getParameter("name");
        if(!"admin".equals(username)){
            log.info("admin 用户认证失败");
            ctx.setResponseStatusCode(401);
            ctx.setSendZuulResponse(false);
            ctx.setResponseBody("admin 用户认证失败");
            ctx.set("isOK",false);//可以把一些值放到ctx中，便于后面的filter获取使用
            return null;
        }
        ctx.set("isOK",true);//可以把一些值放到ctx中，便于后面的filter获取使用
        return null;
    }
}
